package com.wufeng.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wufeng.dto.R;
import com.wufeng.dto.ReplyDto;
import com.wufeng.entity.Article;
import com.wufeng.entity.Reply;
import com.wufeng.entity.ReplyLikeRecord;
import com.wufeng.entity.User;
import com.wufeng.service.ArticleService;
import com.wufeng.service.ReplyLikeRecordService;
import com.wufeng.service.ReplyService;
import com.wufeng.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 *  回复表(Reply)表控制层
 */
@RestController
@RequestMapping("/reply")
public class ReplyController {

    @Autowired
    private ReplyService replyService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    @Autowired
    private ReplyLikeRecordService replyLikeRecordService;

    /**
     * 添加一个回复，同时当前文章的回复数加一
     *
     * @param reply
     * @return
     */
    @Transactional
    @PostMapping("/addReply")
    public R addReply(@RequestBody Reply reply) {
        // 1.保存回复
        boolean isSave = replyService.save(reply);
        // 2.更新文章的回复数
        Boolean isAdd = articleService.addReplycountById(reply.getArticleid());

        Map<String, Object> map = new HashMap<>();
        map.put("isSave", isSave && isAdd);
        return R.ok(map);
    }

    /**
     * 根据文章id获取回复列表
     *
     * @return
     */
    @GetMapping("/getReplyListByArticleId")
    public R getReplyListByArticleId(@RequestParam Integer articleId) {

        QueryWrapper<Reply> wrapper = new QueryWrapper<>();
        wrapper.eq("articleId", articleId);
        List<Reply> list = replyService.list(wrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("list", list);

        return R.ok(map);
    }


    /**
     * 根据回复id删除回复,
     * 同时当前文章的回复数减一
     *
     * @param replyId
     * @return
     */
    @Transactional
    @PostMapping("/deleteReplyById")
    public R deleteReplyById(@RequestParam("replyId") Integer replyId, @RequestParam("articleId") Integer articleId) {

        //删除该回复所有点赞记录
        boolean deleteRecords = replyLikeRecordService.remove(new QueryWrapper<ReplyLikeRecord>().eq("replyId", replyId));

        //删除回复
        boolean deleteReply = replyService.removeById(replyId);

        //文章回复减一
        Boolean isMinus = articleService.minusReplycountById(articleId);

        Map<String, Object> map = new HashMap<>();
        map.put("isDelete", deleteRecords && deleteReply && isMinus);
        return R.ok(map);
    }


    /**
     * 根据用户id获取回复列表
     *
     * @param userId
     * @param isReceiveId 是否是接收者的回复列表，true是，false否
     * @return
     */
    @Transactional
    @GetMapping("/getReplyListByUserId")
    public R getReplyListByUserId(@RequestParam("userId") Integer userId,
                                  @RequestParam(value = "isReceiveId", required = false) Boolean isReceiveId) {

        System.out.println("-------------------------------"+isReceiveId+"------------------------------------");

        // 1. 获取回复列表，并按照 createTime 降序排序
        QueryWrapper<Reply> wrapper = new QueryWrapper<>();
        if (isReceiveId!=null && isReceiveId) {
            System.out.println("-------------------------------if------------------------------------");
            wrapper.eq("receiveId", userId).orderByDesc("createTime");
        } else {
            System.out.println("-------------------------------else------------------------------------");
            wrapper.eq("userId", userId).orderByDesc("createTime");
        }

        List<Reply> replyList = replyService.list(wrapper);

        if(replyList.isEmpty()){
            Map<String, Object> map = new HashMap<>();
            map.put("list", null);
            return R.ok(map);
        }

        // 2. 收集回复的 receiveid，以便获取所有相关用户的信息
        Set<Integer> userIds = replyList.stream().map(Reply::getReceiveid).collect(Collectors.toSet());

        // 3. 查询所有相关的用户
        List<User> userList = userService.list(new QueryWrapper<User>().in("userId", userIds));

        // 4. 创建 ReplyDto 对象，并加入到包含用户名的 list 中
        List<ReplyDto> list = new ArrayList<>();
        for (Reply reply : replyList) {
            ReplyDto replyDto = new ReplyDto();
            BeanUtils.copyProperties(reply, replyDto);

            // 从 userList 中找到对应的用户，并设置用户名
            Optional<User> optionalUser = userList.stream().filter(user -> user.getUserid().equals(reply.getReceiveid())).findFirst();
            optionalUser.ifPresent(user -> replyDto.setUsername(user.getUsername()));

            list.add(replyDto);
        }

        // 5. 将 list 放入响应的 Map 中
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        return R.ok(map);
    }

}
